package com.resou.reader.mine.presenter;

import android.content.Context;
import android.os.CountDownTimer;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.service.UserService;
import com.resou.reader.commom.Constant;
import com.resou.reader.data.Injection;
import com.resou.reader.data.ResouxsRepository;
import com.resou.reader.mine.IView.ILoginView;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.reader.utils.SpUtils;
import com.resou.reader.utils.AppExecutors;
import com.resou.reader.utils.CacheUtils;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.eventbus.RefreshStoreEvent;
import com.resou.reader.utils.log.LogUtil;
import com.resou.reader.utils.log.RsLog;
import com.resou.reader.view.Loading;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Garrett on 2018/8/27.
 * contact me krouky@outlook.com
 */
public class LoginPresenter {
    public static final String TAG = "LoginPresenter";
    private ILoginView mView;

    private CountDownTimer timer;

    private UserService mService;
    private final ResouxsRepository mRepository;

    public LoginPresenter(ILoginView iView) {
        mView = iView;
        mService = Injection.provideUserService();
        mRepository = ResouxsRepository.getInstance();

//        mService = ApiImp.getInstance().getService(UserService.class);
    }

    /**
     * 发送验证码
     */
    public void sendSMSCode(String phone) {
        if (TextUtils.isEmpty(phone)) {
            mView.toastMsg(ReSouApplication.getRSApplication().getString(R.string.user_phone_number_empty));
            return;
        }
        if (phone.length() != 11) {
            mView.toastMsg(ReSouApplication.getRSApplication().getString(R.string.user_phone_number_ill));
            return;
        }

        startCountDownTimer();
        timer.start();//开始计时
        mService.smsSend(phone, Constant.SMS_SEND_TYPE_LOGIN)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Result result) {
                        mView.toastMsg(result.getMsg());
                    }

                    @Override
                    public void onError(Throwable e) {
                        RsLog.i("sendSMS error!" + e.getMessage());
                        e.printStackTrace();
                        mView.toastMsg(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void startCountDownTimer() {
        if (timer == null) {
            timer = new CountDownTimer(60 * 1000, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (mView != null) {
                        mView.updateVerifyText(millisUntilFinished / 1000 + ReSouApplication.getRSApplication().getString(R.string.user_get_code_until_finished), false);
                    } else {
                        timer.cancel();
                    }
                }

                @Override
                public void onFinish() {
                    mView.updateVerifyText(ReSouApplication.getRSApplication().getString(R.string.user_login_get_code), true);
                }
            };
        }
    }

    /**
     * 游客账号合并
     *
     * @param state    状态 0：手机登录、1：微信登录、2：qq登录
     * @param account  账号
     * @param platform 平台
     */
    public void mergeAccount(int state, String account, SHARE_MEDIA platform) {
        mService.mergeAccount(UserInstance.getToken(),
                state == 0 ? account : null, state == 1 ? account : null, state == 2 ? account : null)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Result<String> stringResult) {
                        switch (state) {
                            case 0:
                                mView.phoneLogin();
                                break;
                            case 1:
                                mView.winXinLogin(platform);
                                break;
                            case 2:
                                mView.qqLogin(platform);
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        mView.hideProgress();
                    }

                    @Override
                    public void onComplete() {
                        mView.hideProgress();
                    }
                });
    }


    /**
     * 短信登录
     *
     * @param mobile 电话号码
     * @param code   验证码
     */
    public void smsLogin(final LoginListener loginListener, String mobile, String code) {
        mService.smsLogin(DeviceUtils.getIMEI(ReSouApplication.getRSApplication()), mobile, code, "", Constant.LOGIN_TYPE_CODE, "android")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResult<LoginData>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(LoginResult<LoginData> loginDataLoginResult) {
                        if (loginDataLoginResult.getCode() == 0) {
                            String token = loginDataLoginResult.getToken();
                            if (token != null) {
                                CacheUtils.clearAllCache(mView.getViewContext().getApplicationContext());
                                LoginData data = loginDataLoginResult.getData();
                                UserInstance.setLoginData(data);
                                UserInstance.setToken(token);
                                MobclickAgent.onProfileSignIn("phone_sms", String.valueOf(data.getId()));
                                MobclickAgent.onEvent(ReSouApplication.getRSApplication(), "user_login", "phone_sms");

                                uPshSetting(data.getId());
                                /**
                                 * 同步本地书架到服务器
                                 */
                                EventBus.getDefault().post(new Message());
                                PreferenceUtil.getInstance(mView.getViewContext()).saveSubSidyStateValue(loginDataLoginResult.getData().getReadType());
                                //登录成功后让其他地方更新登录信息
                                MessageEvent event = new MessageEvent();
                                event.isLogin = true;
                                EventBus.getDefault().post(event);
                                EventBus.getDefault().post(new RefreshStoreEvent());

                                syncActivityInfo(mView.getViewContext());
                                saveRechargeActivityState(mView.getViewContext());

                                if (loginListener != null)
                                    //此回调调用的是HomeUserCenterFragment的方法
                                    loginListener.onSuccess(loginDataLoginResult);
                                mView.dismiss();
                            } else {
                                if (loginListener != null) {
                                    loginListener.onError(new Throwable(loginDataLoginResult.getMsg()));
                                }
                            }
                        } else {
                            if (loginListener != null)
                                loginListener.onError(new Throwable(loginDataLoginResult.getMsg()));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (loginListener != null)
                            loginListener.onError(e);
                        mView.hideProgress();
                    }

                    @Override
                    public void onComplete() {
                        mView.hideProgress();
                    }
                });
    }

    //通过友盟第三方登录
    public void login(SHARE_MEDIA platform, String loginType, String unionid, String sex, String name, String icon, LoginListener loginListener) {
        String imei = DeviceUtils.getIMEI(ReSouApplication.getRSApplication());
        mService.thirdLogin(imei, loginType, unionid, sex, name, icon, "android")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResult<LoginData>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(LoginResult<LoginData> loginDataLoginResult) {
                        CacheUtils.clearAllCache(mView.getViewContext().getApplicationContext());
                        String msg = loginDataLoginResult.getMsg();
                        String token = loginDataLoginResult.getToken();
                        LoginData data = loginDataLoginResult.getData();
                        EventBus.getDefault().post(new RefreshStoreEvent());
                        PreferenceUtil.getInstance(mView.getViewContext()).saveSubSidyStateValue(loginDataLoginResult.getData().getReadType());

                        if (loginDataLoginResult.getCode() == 0 && token != null) {
                            //登录成功后保存登录信息
                            UserInstance.setLoginData(data);
                            UserInstance.setToken(token);
                            //统计
                            if (platform == SHARE_MEDIA.WEIXIN) {
                                MobclickAgent.onProfileSignIn("WX", String.valueOf(data.getId()));
                                MobclickAgent.onEvent(ReSouApplication.getRSApplication(), "user_login", "WeiXin");
                            } else if (platform == SHARE_MEDIA.QQ) {
                                MobclickAgent.onProfileSignIn("QQ", String.valueOf(data.getId()));
                                MobclickAgent.onEvent(ReSouApplication.getRSApplication(), "user_login", "QQ");
                            }

                            uPshSetting(data.getId());
                            /**
                             * 同步本地书架到服务器
                             */
                            EventBus.getDefault().post(new Message());

                            //登录成功后让其他地方更新登录信息
                            MessageEvent event = new MessageEvent();
                            event.isLogin = true;
                            EventBus.getDefault().post(event);
                            EventBus.getDefault().post(new RefreshStoreEvent());

                            syncActivityInfo(mView.getViewContext());
                            saveRechargeActivityState(mView.getViewContext());

                            if (loginListener != null) {
                                //登录成功后回调MainActivity的成功回调
                                loginListener.onSuccess(loginDataLoginResult);
                            }
//                            Loading.getInstance().dismiss();
                        } else {
                            if (loginListener != null)
                                loginListener.onError(new Throwable(msg));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (loginListener != null)
                            loginListener.onError(e);
                        mView.hideProgress();
                    }

                    @Override
                    public void onComplete() {
                        mView.hideProgress();
                    }
                });
    }

    public void onViewDismiss() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void uPshSetting(int userId) {
        final PushAgent mPushAgent = PushAgent.getInstance(ReSouApplication.getRSApplication());
        mPushAgent.setAlias(String.valueOf(userId), "type_id", new UTrack.ICallBack() {

            @Override
            public void onMessage(boolean isSuccess, String message) {

            }
        });
    }


    /**
     * 同步活动信息
     */
    public void syncActivityInfo(Context context) {
        /**
         * 检测是否参加过十五日免费阅读活动
         */
        AppExecutors.getAppExecutors().networkIO().execute(() -> {
            if (UserInstance.isLogin()) {
                String token = UserInstance.getToken();
                Boolean isInActivity = mRepository.checkIsInActivity(token);
                if (isInActivity) {
                    //参加过活动
                    PreferenceUtil.getInstance(context.getApplicationContext()).setNeverShowFifteenDaysDialogState();
                } else {
                    //未参加过
                    //校验是否应该弹出窗口
                    Boolean shouldOpenDialog = mRepository.checkIsShouldOpenDialog(token, "android");
                    if (shouldOpenDialog) {
                        PreferenceUtil.getInstance(context.getApplicationContext()).setShowFifteenDaysDialog();
                    }
                }
            }
        });
    }

    /**
     * 从服务器读三天充值状态
     *
     * @param context
     */
    public void saveRechargeActivityState(Context context) {
        AppExecutors.getAppExecutors().networkIO().execute(() -> {
            Boolean isJoin = mRepository.checkRechargeActivity(UserInstance.getToken());
            Log.i("充值", "saveRechargeActivityState: " + isJoin);
            PreferenceUtil.getInstance(context).setShowRechargeDialogToday(!isJoin);
        });
    }


}
